export function get(binaryId) {
  return RSocket.rr({
    route: `files.${ROUTE(binaryId)}`,
  });
}

export function getMeta(binaryId) {
  return RSocket.rr({
    route: `files.${ROUTE(binaryId)}.meta`,
  });
}

export function upload({ binaryId, mimeType, filename, arrayBuffer }) {
  return RSocket.rc({
    route: 'files.upload',
    args: {
      binary: {
        binaryId,
        mimeType,
        filename,
      },
    },
    data: Buffer.from(arrayBuffer),
  });
}

export function customRequest({ file, binaryId, mimeType, filename, onSuccess, onError, onLoading }) {
  const reader = new FileReader();
  reader.onloadend = async () => {
    onLoading?.(true);
    try {
      await upload({
        binaryId,
        mimeType: mimeType || filename.type,
        filename: filename || filename.filename,
        arrayBuffer: reader.result,
      });
      onSuccess?.(file);
    } catch (e) {
      onError?.(e);
    } finally {
      onLoading?.(false);
    }
  };
  reader.readAsArrayBuffer(file);
}
